package red.mlz.module.module.category.service;


import org.springframework.stereotype.Service;
import red.mlz.module.module.category.entity.Category;
import red.mlz.module.module.category.mapper.CategoryMapper;
import red.mlz.module.module.user.service.BaseUserService;
import red.mlz.module.utils.BaseUtils;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;

/**
 * <p>
 * 分类表 服务类
 * </p>
 *
 * @author mlzred
 * @since 2025-04-03
 */
@Service
public class CategoryService {

    @Resource
    private CategoryMapper  mapper;


    public Category getById(BigInteger id) {
        return mapper.getById(id);
    }

    public Category extractById(BigInteger id) {
        return mapper.extractById(id);
    }

    public void insert(Category category) {
        mapper.insert(category);
    }

    public int update(Category category) {
        return mapper.update(category);
    }

    public void delete(BigInteger id) {
        mapper.delete(id, BaseUtils.currentSeconds());
    }
    public List<BigInteger> getIdsByName(String keyname) {
        return mapper.getIdsByName(keyname);
    }

    public List<Category> getCategoryList(int page, int pageSize, String key) {
        int begin = (page - 1) * pageSize;
        return mapper.getCategoryList(begin, pageSize, key);

    }

    public BigInteger editCategory(BigInteger categoryId, String name, String imageUrl, BigInteger parentId) {
        Category category = new Category();
        category.setId(categoryId);
        category.setName(name);
        category.setImageUrl(imageUrl);
        category.setParentId(parentId);
        category.setIsDeleted(0);
        if (BaseUtils.isEmpty(parentId)){
            category.setParentId(BigInteger.valueOf(0));
        }

        if (BaseUtils.isEmpty(categoryId)){
            category.setCreateTime(BaseUtils.currentSeconds());
            insert(category);
        }else {
            Category old = getById(categoryId);
            if (BaseUtils.isEmpty(old)){
                throw new RuntimeException("edit category error, old not exist");
            }
            category.setId(categoryId);
            category.setUpdateTime(BaseUtils.currentSeconds());
            update(category);
        }
        return category.getId();
    }

    public List<Category> categoryList() {
        List<Category> categoryList = mapper.listByIdsAndParentIds(null,null);
        // 如果为空
        return categoryList;
    }


    public List<Category> listByIds(String allCategoryIds) {
        return mapper.listByIdsAndParentIds(allCategoryIds,null);
    }

//    public List<Category> list(String parentId) {
//        return mapper.listByIdsAndParentIds(null,parentId);
//    }

    public List<Category> listByParentId(String parentId) {
        return mapper.listByIdsAndParentIds(null,parentId);
    }
}
